<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    class="demo-ruleForm"
  >
    <el-form-item prop="username">
      <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="ruleForm.password"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="loginFn()">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref } from "vue";
import { useRouter } from "vue-router";
import Cookie from "js-cookie";
import { adminLoginApi ,getAdminInfoApi} from "../../request/api";
import {useStore} from "vuex";
const state = reactive({
  ruleForm: {
    username: "admin",
    password: "123456",
  },
});

// 获取el-form表单组件对象
const ruleFormRef = ref();

// 获取项目路由对象
const router = useRouter();

// 获取项目vuex对象
let store = useStore();

const validateUsername = (
  rule: unknown,
  value: string | undefined,
  callback: (msg?: string) => void
) => {
  if (!value) {
    callback("用户名不能为空！");
  } else {
    callback();
  }
};

const validatePwd = (
  rule: unknown,
  value: string | undefined,
  callback: (msg?: string) => void
) => {
  if (!value) {
    callback("密码不能为空！");
  } else {
    callback();
  }
};
// 校验规则
const rules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePwd, trigger: "blur" }],
});
// 点击登录触发 事件
const loginFn = () => {
  ruleFormRef.value
    .validate()
    .then(() => {
      console.log("校验通过");
      adminLoginApi({
        password: ruleForm.value.password,
        username: ruleForm.value.username,
      }).then((res) => {
        if (res.code === 200) {
          // 储存token
          Cookie.set("token", res.data.tokenHead + res.data.token, {
            expires: 7,
          });
          // 获取用户信息
          getAdminInfoApi().then(res=>{
            // res.code
            if(res.code === 200){
              // 存储vuex
              store.commit("updateMenus",res.data.menus)
              router.push("/home")
            }
          })
        }
      });
    })
    .catch(() => {
      console.log("校验不通过");
    });
};

let { ruleForm } = toRefs(state);
</script>

<style lang="less" scoped></style>
